// 公共工具类
class Utils {
    // API基础配置
    static get API_BASE_URL() {
        // 切回原始基础URL，参考登录接口的实现方式
        return 'http://localhost:8080';
    }

    // 获取完整的API URL
    static getApiUrl(endpoint) {
        // 如果endpoint已经是完整URL，直接返回
        if (endpoint.startsWith('http')) {
            console.log('使用完整URL:', endpoint);
            return endpoint;
        }
        // 确保endpoint以斜杠开头
        if (!endpoint.startsWith('/')) {
            endpoint = '/' + endpoint;
        }
        const fullUrl = `${this.API_BASE_URL}${endpoint}`;
        console.log('构建API URL - 原始路径:', endpoint, '完整URL:', fullUrl);
        return fullUrl;
        // 注意：根据登录接口的实现方式，前端API调用时需在路径中包含/chm前缀，如'/chm/api/auth/login'
    }
    // 显示提示信息
    static showAlert(message, type = 'info') {
        const alertDiv = document.createElement('div');
        const bgColor = type === 'error' ? 'bg-red-50' : type === 'success' ? 'bg-green-50' : 'bg-blue-50';
        const borderColor = type === 'error' ? 'border-red-200' : type === 'success' ? 'border-green-200' : 'border-blue-200';
        const textColor = type === 'error' ? 'text-red-800' : type === 'success' ? 'text-green-800' : 'text-blue-800';

        alertDiv.className = `fixed top-4 right-4 z-50 ${bgColor} border ${borderColor} ${textColor} px-4 py-3 rounded-lg shadow-lg max-w-sm transition-all duration-300 transform translate-x-full`;
        alertDiv.innerHTML = `
            <div class="flex items-center">
                <span class="mr-2">${type === 'error' ? '❌' : type === 'success' ? '✅' : 'ℹ️'}</span>
                <span class="font-medium">${message}</span>
                <button class="ml-auto text-gray-500 hover:text-gray-700" onclick="this.parentElement.parentElement.remove()">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
        `;

        document.body.appendChild(alertDiv);

        // 动画显示
        setTimeout(() => {
            alertDiv.classList.remove('translate-x-full');
            alertDiv.classList.add('translate-x-0');
        }, 10);

        // 自动消失
        setTimeout(() => {
            if (alertDiv.parentElement) {
                alertDiv.classList.remove('translate-x-0');
                alertDiv.classList.add('translate-x-full');
                setTimeout(() => {
                    if (alertDiv.parentElement) {
                        alertDiv.remove();
                    }
                }, 300);
            }
        }, 4000);
    }

    // 获取用户信息
    static getUserInfo() {
        try {
            return {
                realName: localStorage.getItem('auth.realName') || '管理员',
                username: localStorage.getItem('auth.username') || ''
            };
        } catch (e) {
            return { realName: '管理员', username: '' };
        }
    }

    // 退出登录
    static logout() {
        try {
            localStorage.removeItem('auth.loggedIn');
            localStorage.removeItem('auth.token');
            localStorage.removeItem('auth.userId');
            localStorage.removeItem('auth.username');
            localStorage.removeItem('auth.realName');
            localStorage.removeItem('auth.email');
        } catch (e) {}
        window.location.href = 'login.html';
    }

    // 格式化日期
    static formatDate(dateString) {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 检查是否登录
    static checkLogin() {
        try {
            return localStorage.getItem('auth.loggedIn') === 'true';
        } catch (e) {
            return false;
        }
    }

    // API请求封装
    static async apiRequest(url, options = {}) {
        const token = localStorage.getItem('auth.token');
        const defaultOptions = {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
                ...options.headers
            }
        };

        try {
            const response = await fetch(url, { ...defaultOptions, ...options });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            return result;
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 分页组件 - 紧凑风格
    static Pagination({ currentPage, totalPages, totalCount, itemsPerPage, onPageChange, onItemsPerPageChange }) {
        // 计算显示的页码范围（紧凑风格显示更少页码）
        const getPageNumbers = () => {
            if (totalPages <= 5) {
                // 总页数小于等于5时显示所有页码
                return Array.from({ length: totalPages }, (_, i) => i + 1);
            }

            const range = [];
            const delta = 1; // 当前页前后显示1页，减少显示的页码数

            // 始终显示第一页
            range.push(1);

            // 计算起始和结束页码
            let start = Math.max(2, currentPage - delta);
            let end = Math.min(totalPages - 1, currentPage + delta);

            // 调整范围确保显示足够的页码
            if (currentPage - delta <= 2) {
                end = Math.min(totalPages - 1, 3);
            }

            if (currentPage + delta >= totalPages - 1) {
                start = Math.max(2, totalPages - 2);
            }

            // 添加起始省略号
            if (start > 2) {
                range.push('...');
            }

            // 添加中间页码
            for (let i = start; i <= end; i++) {
                range.push(i);
            }

            // 添加结束省略号
            if (end < totalPages - 1) {
                range.push('...');
            }

            // 始终显示最后一页
            range.push(totalPages);

            return range;
        };

        // 计算显示的数据范围
        const startItem = (currentPage - 1) * itemsPerPage + 1;
        const endItem = Math.min(currentPage * itemsPerPage, totalCount);

        // 处理页码跳转 - 移除useRef，使用React的受控组件模式
        const handleGoToPage = (e) => {
            // 获取父元素中的输入框值
            const inputElement = e.currentTarget.previousElementSibling.previousElementSibling;
            if (inputElement) {
                let page = parseInt(inputElement.value);
                if (!isNaN(page) && page >= 1 && page <= totalPages) {
                    onPageChange(page);
                } else {
                    // 如果输入无效，重置为当前页码
                    inputElement.value = currentPage.toString();
                }
            }
        };
        
        // 处理回车键
        const handleKeyPress = (e, page) => {
            if (e.key === 'Enter') {
                const inputValue = e.target.value;
                const pageNum = parseInt(inputValue);
                if (!isNaN(pageNum) && pageNum >= 1 && pageNum <= totalPages) {
                    onPageChange(pageNum);
                } else {
                    e.target.value = page.toString();
                }
            }
        };

        return React.createElement('div', {
                className: 'flex flex-wrap items-center justify-between px-4 py-3 border-t border-gray-200 text-sm'
            },
            // 左侧：数据统计和每页条数选择
            React.createElement('div', { className: 'flex items-center space-x-6 mb-2 sm:mb-0' },
                // 数据统计信息
                React.createElement('div', { className: 'text-gray-600' },
                    `显示第 ${startItem}-${endItem} 条，共 ${totalCount} 条记录`
                ),

                // 每页条数选择
                React.createElement('div', { className: 'flex items-center space-x-1' },
                    React.createElement('span', { className: 'text-gray-600' }, '每页'),
                    React.createElement('select', {
                            className: 'text-sm border border-gray-300 rounded px-2 py-1 bg-white h-8',
                            value: itemsPerPage,
                            onChange: (e) => {
                                // 每页条数改变时，获取新值并触发回调
                                const newSize = parseInt(e.target.value);
                                // 调用onItemsPerPageChange回调，通知父组件每页条数已改变
                                if (typeof onItemsPerPageChange === 'function') {
                                    onItemsPerPageChange(newSize);
                                }
                                // 同时重置到第1页以重新加载列表
                                if (typeof onPageChange === 'function') {
                                    onPageChange(1);
                                }
                            }
                        },
                        [10, 20, 50, 100].map(size =>
                            React.createElement('option', { key: size, value: size }, size)
                        )
                    ),
                    React.createElement('span', { className: 'text-gray-600' }, '条')
                )
            ),

            // 右侧：分页导航和快速跳转
            React.createElement('div', { className: 'flex items-center space-x-2' },
                // 分页导航栏 - 紧凑样式
                totalPages > 1 && React.createElement('div', { className: 'flex items-center space-x-0' },
                    // 第一页按钮 - 简化为图标
                    React.createElement('button', {
                            onClick: () => onPageChange(1),
                            disabled: currentPage === 1,
                            className: `p-2 text-sm ${currentPage === 1 ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-blue-600'}`
                        },
                        React.createElement('svg', {
                                className: 'w-4 h-4',
                                fill: 'none',
                                stroke: 'currentColor',
                                viewBox: '0 0 24 24'
                            },
                            React.createElement('path', {
                                strokeLinecap: 'round',
                                strokeLinejoin: 'round',
                                strokeWidth: '2',
                                d: 'M11 19l-7-7 7-7m8 14l-7-7 7-7'
                            })
                        )
                    ),

                    // 上一页按钮 - 简化为图标
                    React.createElement('button', {
                            onClick: () => onPageChange(currentPage - 1),
                            disabled: currentPage === 1,
                            className: `p-2 text-sm rounded ${currentPage === 1 ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-blue-600'}`
                        },
                        React.createElement('svg', {
                                className: 'w-4 h-4',
                                fill: 'none',
                                stroke: 'currentColor',
                                viewBox: '0 0 24 24'
                            },
                            React.createElement('path', {
                                strokeLinecap: 'round',
                                strokeLinejoin: 'round',
                                strokeWidth: '2',
                                d: 'M15 19l-7-7 7-7'
                            })
                        )
                    ),

                    // 页码按钮区域 - 减小尺寸
                    getPageNumbers().map((page, index) =>
                        page === '...' ?
                            React.createElement('span', {
                                key: `dots-${index}`,
                                className: 'p-2 text-sm text-gray-500'
                            }, '...') :
                            React.createElement('button', {
                                key: page,
                                onClick: () => onPageChange(page),
                                className: `w-8 h-8 flex items-center justify-center text-sm ${currentPage === page ? 'bg-blue-600 text-white rounded' : 'text-gray-700 hover:bg-gray-100'}`
                            }, page)
                    ),

                    // 下一页按钮 - 简化为图标
                    React.createElement('button', {
                            onClick: () => onPageChange(currentPage + 1),
                            disabled: currentPage === totalPages,
                            className: `p-2 text-sm rounded ${currentPage === totalPages ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-blue-600'}`
                        },
                        React.createElement('svg', {
                                className: 'w-4 h-4',
                                fill: 'none',
                                stroke: 'currentColor',
                                viewBox: '0 0 24 24'
                            },
                            React.createElement('path', {
                                strokeLinecap: 'round',
                                strokeLinejoin: 'round',
                                strokeWidth: '2',
                                d: 'M9 5l7 7-7 7'
                            })
                        )
                    ),

                    // 最后一页按钮 - 简化为图标
                    React.createElement('button', {
                            onClick: () => onPageChange(totalPages),
                            disabled: currentPage === totalPages,
                            className: `p-2 text-sm ${currentPage === totalPages ? 'text-gray-300 cursor-not-allowed' : 'text-gray-600 hover:text-blue-600'}`
                        },
                        React.createElement('svg', {
                                className: 'w-4 h-4',
                                fill: 'none',
                                stroke: 'currentColor',
                                viewBox: '0 0 24 24'
                            },
                            React.createElement('path', {
                                strokeLinecap: 'round',
                                strokeLinejoin: 'round',
                                strokeWidth: '2',
                                d: 'M13 5l7 7-7 7M5 5l7 7-7 7'
                            })
                        )
                    )
                ),

                // 快速跳转 - 简化样式
                React.createElement('div', { className: 'flex items-center space-x-1' },
                    React.createElement('span', { className: 'text-sm text-gray-600' }, '跳转到'),
                    React.createElement('input', {
                        type: 'number',
                        min: 1,
                        max: totalPages,
                        defaultValue: currentPage.toString(),
                        className: 'w-14 h-8 text-sm border border-gray-300 rounded px-2 text-center',
                        onKeyPress: (e) => handleKeyPress(e, currentPage)
                    }),
                    React.createElement('span', { className: 'text-sm text-gray-600' }, '页'),
                    React.createElement('button', {
                        className: 'px-3 h-8 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition',
                        onClick: handleGoToPage
                    }, '确定')
                )
            )
        );
    }
}

// 在现有utils.js中添加以下代码

// 通用数据获取函数
Utils.fetchData = async (url, options = {}) => {
    const token = localStorage.getItem('auth.token');
    const defaultOptions = {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            ...options.headers
        },
        mode: 'cors',
        credentials: 'omit',
        ...options
    };
    
    // 将fullUrl移到try块外部，确保在catch块中也能访问
    const fullUrl = Utils.getApiUrl(url);
    
    try {
        const response = await fetch(fullUrl, defaultOptions);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}, URL: ${fullUrl}`);
        }
        
        const result = await response.json();
        if (result.status !== 0) {
            throw new Error(`请求失败 (${fullUrl}): ${result.msg || '未知错误'}`);
        }
        
        return result;
    } catch (error) {
        console.error('API请求错误 (URL: ' + fullUrl + '):', error);
        throw error;
    }
};

// 确保所有API操作方法都明确使用getApiUrl构建URL
Utils.createItem = async (url, data) => {
    const fullUrl = Utils.getApiUrl(url);
    console.log('创建项目 - 请求URL:', fullUrl);
    return Utils.fetchData(fullUrl, {
        method: 'POST',
        body: JSON.stringify(data)
    });
};

Utils.updateItem = async (url, data) => {
    const fullUrl = Utils.getApiUrl(url);
    console.log('更新项目 - 请求URL:', fullUrl);
    return Utils.fetchData(fullUrl, {
        method: 'PUT',
        body: JSON.stringify(data)
    });
};

Utils.deleteItem = async (url) => {
    const fullUrl = Utils.getApiUrl(url);
    console.log('删除项目 - 请求URL:', fullUrl);
    return Utils.fetchData(fullUrl, {
        method: 'DELETE'
    });
};

// 确保showAlert函数存在
if (!Utils.showAlert) {
    Utils.showAlert = (message, type = 'info') => {
        alert(message);
    };
}

// 将Utils类暴露到全局作用域，以便在其他文件中访问
window.Utils = Utils;